package com.seka.control.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/** 
 * 发送请求
 * @author mw
 * @version 1.0.0
 */
public class HttpGetUtil {
	/**连接时间*/
	private static final int CONNECT_TIMEOUT = 60000;
	/**读取时间*/
	private static final int READ_TIMEOUT = 1500000;
	/**编码*/
	private static final String ENCODING = "UTF-8";

	/**
	 * 发送http请求
	 * @param urlStr 地址
	 * @return String 相应信息
	 */
	public static String get(String urlStr) throws IOException {
		BufferedReader br = null;
		HttpURLConnection urlconn = null;
		OutputStream out = null;
		try {
			URL url = new URL(urlStr);
			urlconn = (HttpURLConnection) url.openConnection();
			urlconn.setRequestProperty("Content-type", "application/xml;charset=" + ENCODING);
			urlconn.setConnectTimeout(CONNECT_TIMEOUT);
			urlconn.setReadTimeout(READ_TIMEOUT);
			urlconn.setRequestMethod("GET");
			urlconn.setUseCaches(false);
			urlconn.setDoOutput(true);
			urlconn.setDoInput(true);
			// 发送请求
			{
				out = urlconn.getOutputStream();
				out.flush();
				out.close();
				out = null;
			}

			// 处理响应
			char[] charBuf = new char[1024];
			int readChars = -1;
			StringBuffer res = new StringBuffer();
			InputStream inStrm = urlconn.getInputStream();
			br = new BufferedReader(new InputStreamReader(inStrm, ENCODING));
			while ((readChars = br.read(charBuf)) != -1) {
				res.append(charBuf, 0, readChars);
			}
			br.close();
			urlconn.disconnect();
			urlconn = null;
			return res.toString();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (br != null) {
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (urlconn != null) {
				urlconn.disconnect();
			}
		}
	}

}